/**
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.castannon.axis2.guice;

import org.apache.axis2.AxisFault;
import org.apache.axis2.ServiceObjectSupplier;
import org.apache.axis2.description.AxisService;
import org.apache.axis2.description.Parameter;
import org.apache.axis2.i18n.Messages;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.inject.Injector;

/**
 * 
 * @author David Castañón (dcastannon)
 *
 */
public class GuiceServiceObjectSupplier implements ServiceObjectSupplier {
    private final static Logger log = LoggerFactory
	    .getLogger(GuiceServiceObjectSupplier.class);

    public Object getServiceObject(AxisService service) throws AxisFault {

	log.debug("Supplying Guice service object for {} service", service
		.getKey());
	try {
	    String className;
	    {
		Parameter parameter = service.getParameter("ServiceClass");
		if (parameter == null)
		    throw new AxisFault(Messages.getMessage(
			    "paramIsNotSpecified", "ServiceClass"));
		className = ((String) parameter.getValue()).trim();
	    }

	    log.debug("The serviceClass is {}", className);

	    Class<?> serviceClass = (Class<?>) Class.forName(className, false,
		    service.getClassLoader());

	    String injectorKey = "defaultInjector";
	    {
		Parameter parameter = service.getParameter("InjectorKey");
		if (parameter != null)
		    injectorKey = ((String) parameter.getValue()).trim();
	    }
	    log.debug("The injector key is {}", injectorKey);
	    Injector injector = GuiceInjectorHolder.getInjector(injectorKey);
	    if (injector == null)
		throw new AxisFault("GuiceInjectorHolder not initialized");

	    Object serviceObject = injector.getInstance(serviceClass);
	    log.debug("Service object created");
	    return serviceObject;
	} catch (Exception e) {
	    log.debug("GuiceServiceObjectSupplier", e);
	    throw AxisFault.makeFault(e);
	}

    }
}
